<template>
  <div class="leave-application-container">
    <span class="page-header">
      <!-- 返回按钮 -->
      <button class="back-button" @click="goBack">返回</button>
      <!-- 列表链接 -->
      <span>
        <router-link to="/main/renshi/kaoqing/qingjia-list"><button class="back-button">列表</button></router-link>
        <!-- 流程按钮 -->
        <router-link :to="{
          path: '/main/renshi/kaoqing/qingjia-process',
          query: { id: formData.id }
        }" v-if="formData.id"><button class="back-button">流程</button></router-link>
        <button class="back-button" @click="printForm">打印</button>
      </span>
    </span>
    <div class="container">
      <!-- 页面标题 -->
      <h2 class="page-title">请 假 单</h2>
      <!-- 表单部分 -->
      <div class="form-container">
        <p class="form-label" style="text-align: left;">NO：<input style="width: 20%;" v-model="formData.no"
            class="form-input1" /></p>
        <table class="form-table">
          <tbody>
            <!-- 基本信息 -->
            <tr>
              <td class="table-label">姓 名</td>
              <td><input v-model="formData.name" class="form-input" /></td>
              <td class="table-label">工 号</td>
              <td><input v-model="formData.employeeId" class="form-input" /></td>
            </tr>
            <tr>
              <td class="table-label">部 门</td>
              <td><input v-model="formData.department" class="form-input" /></td>
              <td class="table-label">组 别</td>
              <td><input v-model="formData.groupName" class="form-input" /></td>
            </tr>
            <tr>
              <td class="table-label">级 别</td>
              <td><input v-model="formData.level" class="form-input" /></td>
              <td class="table-label">班 次</td>
              <td><input v-model="formData.shift" class="form-input" /></td>
            </tr>
            <tr>
              <td class="table-label">假 别</td>
              <td><input v-model="formData.leaveType" class="form-input" /></td>
              <td class="table-label">工作代理人</td>
              <td><input v-model="formData.workAgent" class="form-input" /></td>
            </tr>
            <tr>
              <td class="table-label">事 由</td>
              <td colspan="3"><textarea v-model="formData.reason" class="form-textarea"></textarea></td>
            </tr>
            <!-- 拟请假时间 -->
            <tr>
              <td rowspan="3" class="table-label">拟请假</td>
              <td class="table-label">起：</td>
              <td colspan="2">
                <input v-model="formData.plannedStartDate" type="date" class="form-input" />
                <input v-model="formData.plannedStartTime" type="time" class="form-input" />
              </td>
            </tr>
            <tr>
              <td class="table-label">止：</td>
              <td colspan="2">
                <input v-model="formData.plannedEndDate" type="date" class="form-input" />
                <input v-model="formData.plannedEndTime" type="time" class="form-input" />
              </td>
            </tr>
            <tr>
              <td class="table-label">共计：</td>
              <td colspan="2">
                <input v-model="formData.plannedDays" type="number" class="form-input" /> 天
                <input v-model="formData.plannedHours" type="number" class="form-input" /> 小时
              </td>
            </tr>
            <!-- 实际请假时间 -->
            <tr>
              <td rowspan="3" class="table-label">实际请假</td>
              <td class="table-label">起：</td>
              <td colspan="2">
                <input v-model="formData.actualStartDate" type="date" class="form-input" />
                <input v-model="formData.actualStartTime" type="time" class="form-input" />
              </td>
            </tr>
            <tr>
              <td class="table-label">止：</td>
              <td colspan="2">
                <input v-model="formData.actualEndDate" type="date" class="form-input" />
                <input v-model="formData.actualEndTime" type="time" class="form-input" />
              </td>
            </tr>
            <tr>
              <td class="table-label">共计：</td>
              <td colspan="2">
                <input v-model="formData.actualDays" type="number" class="form-input" /> 天
                <input v-model="formData.actualHours" type="number" class="form-input" /> 小时
              </td>
            </tr>
            <!-- 签批信息 -->
            <tr>
              <td class="table-label">申请人</td>
              <td><input v-model="formData.applicant" class="form-input" /></td>
              <td class="table-label">班 组</td>
              <td><input v-model="formData.groupApproval" class="form-input" /></td>
            </tr>
            <tr>
              <td class="table-label">部门主管</td>
              <td><input v-model="formData.departmentSupervisorApproval" class="form-input" /></td>
              <td class="table-label">部门经理</td>
              <td><input v-model="formData.departmentManagerApproval" class="form-input" /></td>
            </tr>
            <tr>
              <td class="table-label">部长/总监</td>
              <td><input v-model="formData.directorApproval" class="form-input" /></td>
              <td class="table-label">总经理</td>
              <td><input v-model="formData.generalManagerApproval" class="form-input" /></td>
            </tr>
            <tr>
              <td class="table-label">总裁/董事长</td>
              <td><input v-model="formData.presidentApproval" class="form-input" /></td>
              <td class="table-label">企业管理部</td>
              <td><input v-model="formData.managementDepartmentApproval" class="form-input" /></td>
            </tr>
          </tbody>
        </table>
        <!-- 保存按钮 -->
        <button class="save-button" @click="saveData">保存</button>
      </div>
      <!-- 附加说明部分 -->
      <div class="additional-info">
        <p>附：</p>
        <p>1、请假流程：</p>
        <p>2、签批流程详见考勤管理办法</p>
        <p style="display: flex;justify-content: space-between;"><span>表单编号及版本：AM - JY - 193 B/2</span>
          <span>保存期限：长期</span>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import { saveLeaveApplication, updateLeaveApplication, getLeaveApplicationDetail } from '@/api/leave';

export default {
  data() {
    return {
      formData: {
        id: null,
      
        no: '',  // 示例自动生成编号，实际应调用generateNo()
        name: '',
        employeeId: '',
        department: '',
        groupName: '',
        level: '',
        shift: '',
        leaveType: '',
        workAgent: '',
        reason: '',
        plannedStartDate: '',
        plannedStartTime: '',
        plannedEndDate: '',
        plannedEndTime: '',
        plannedDays: '',
        plannedHours: '',
        actualStartDate: '',
        actualStartTime: '',
        actualEndDate: '',
        actualEndTime: '',
        actualDays: '',
        actualHours: '',
        applicant: '',
        groupApproval: '',
        departmentSupervisorApproval: '',
        departmentManagerApproval: '',
        directorApproval: '',
        generalManagerApproval: '',
        presidentApproval: '',
        managementDepartmentApproval: ''
      },
      isView: false
    };
  },
  created() {
    const id = this.$route.query.id;
    const type = this.$route.query.type;

    if (id) {
      this.isView = type === 'view';
      this.fetchData(id);
    }
    
    // 添加 postMessage 事件监听
    window.addEventListener('message', this.handlePostMessage);
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听，避免内存泄漏
    window.removeEventListener('message', this.handlePostMessage);
  },
  methods: {
    // 处理接收到的 postMessage 消息
    handlePostMessage(event) {
      // 可以根据需要添加来源验证
      // if (event.origin !== "允许的域名") return;
      
      console.log('收到 postMessage 消息:', event.data);
      
      try {
        const data = event.data;
        
        // 检查消息是否包含有效数据
        if (!data || typeof data !== 'object') return;
        
        // 避免处理自己发送的响应消息
        if (data.type === 'qingjia-response') return;
        
        // 更新表单数据
        // 遍历接收到的数据对象，更新对应的表单字段
        Object.keys(data).forEach(key => {
          // 检查 formData 中是否存在该字段
          if (this.formData.hasOwnProperty(key)) {
            // 特殊处理日期时间字段
            if (key === 'plannedStartTime' && typeof data[key] === 'string' && data[key].includes('T')) {
              const date = new Date(data[key]);
              this.formData.plannedStartDate = date.toISOString().split('T')[0];
              this.formData.plannedStartTime = date.toTimeString().substring(0, 5);
            } else if (key === 'plannedEndTime' && typeof data[key] === 'string' && data[key].includes('T')) {
              const date = new Date(data[key]);
              this.formData.plannedEndDate = date.toISOString().split('T')[0];
              this.formData.plannedEndTime = date.toTimeString().substring(0, 5);
            } else if (key === 'actualStartTime' && typeof data[key] === 'string' && data[key].includes('T')) {
              const date = new Date(data[key]);
              this.formData.actualStartDate = date.toISOString().split('T')[0];
              this.formData.actualStartTime = date.toTimeString().substring(0, 5);
            } else if (key === 'actualEndTime' && typeof data[key] === 'string' && data[key].includes('T')) {
              const date = new Date(data[key]);
              this.formData.actualEndDate = date.toISOString().split('T')[0];
              this.formData.actualEndTime = date.toTimeString().substring(0, 5);
            } else {
              // 直接更新其他字段
              this.formData[key] = data[key];
            }
          }
        });
        
        // 可选：发送响应消息确认接收成功
        if (event.source && event.origin !== 'null') {
          event.source.postMessage({
            type: 'qingjia-response',
            success: true,
            message: '表单数据已更新'
          }, event.origin);
        }
      } catch (error) {
        console.error('处理 postMessage 消息时出错:', error);
        
        // 可选：发送错误响应
        if (event.source && event.origin !== 'null') {
          event.source.postMessage({
            type: 'qingjia-response',
            success: false,
            message: '处理消息时出错'
          }, event.origin);
        }
      }
    },
    
    goBack() {
      // 返回上一页
      this.$router.back();
    },
    async fetchData(id) {
      try {
        const response = await getLeaveApplicationDetail(id);
        if (response.data) {
          const data = response.data;
          // 处理日期和时间
          if (data.plannedStartTime) {
            const date = new Date(data.plannedStartTime);
            this.formData.plannedStartDate = date.toISOString().split('T')[0];
            this.formData.plannedStartTime = date.toTimeString().substring(0, 5);
          }
          if (data.plannedEndTime) {
            const date = new Date(data.plannedEndTime);
            this.formData.plannedEndDate = date.toISOString().split('T')[0];
            this.formData.plannedEndTime = date.toTimeString().substring(0, 5);
          }
          if (data.actualStartTime) {
            const date = new Date(data.actualStartTime);
            this.formData.actualStartDate = date.toISOString().split('T')[0];
            this.formData.actualStartTime = date.toTimeString().substring(0, 5);
          }
          if (data.actualEndTime) {
            const date = new Date(data.actualEndTime);
            this.formData.actualEndDate = date.toISOString().split('T')[0];
            this.formData.actualEndTime = date.toTimeString().substring(0, 5);
          }
          // 设置其他字段
          this.formData = {
            ...this.formData,
            ...data,
            // 保持分离的日期和时间字段
            plannedStartDate: this.formData.plannedStartDate,
            plannedStartTime: this.formData.plannedStartTime,
            plannedEndDate: this.formData.plannedEndDate,
            plannedEndTime: this.formData.plannedEndTime,
            actualStartDate: this.formData.actualStartDate,
            actualStartTime: this.formData.actualStartTime,
            actualEndDate: this.formData.actualEndDate,
            actualEndTime: this.formData.actualEndTime
          };
        }
      } catch (error) {
        this.$message.error('获取数据失败：' + error.message);
      }
    },
    combineDateAndTime(date, time) {
      if (!date || !time) return null;
      try {
        const formattedTime = time.length === 5 ? `${time}:00` : time;
        // 使用标准的日期时间格式
        const [yearStr, monthStr, dayStr] = date.split('-');
        const [hoursStr, minutesStr] = formattedTime.split(':');
        const dateObj = new Date(yearStr, parseInt(monthStr) - 1, dayStr, hoursStr, minutesStr);

        const formattedYear = dateObj.getFullYear();
        const formattedMonth = String(dateObj.getMonth() + 1).padStart(2, '0');
        const formattedDay = String(dateObj.getDate()).padStart(2, '0');
        const formattedHours = String(dateObj.getHours()).padStart(2, '0');
        const formattedMinutes = String(dateObj.getMinutes()).padStart(2, '0');
        const seconds = String(dateObj.getSeconds()).padStart(2, '0');
        return `${formattedYear}-${formattedMonth}-${formattedDay} ${formattedHours}:${formattedMinutes}:${seconds}`;
      } catch (error) {
        console.error('Date parsing error:', error);
        return null;
      }
    },
    generateNo() {
      // 生成格式：年月日 + 4位随机数
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
      return `${year}${month}${day}${random}`;
    },
    async saveData() {
      try {
        // 打印原始表单数据
        console.log('Original form data:', this.formData);

        // 如果是新增，重新生成编号
        if (!this.formData.id) {
          this.formData.no = this.generateNo();
        }

        // 验证必填字段
        if (!this.formData.no) throw new Error('请填写申请编号');
        if (!this.formData.name) throw new Error('请填写姓名');
        if (!this.formData.employeeId) throw new Error('请填写工号');
        if (!this.formData.department) throw new Error('请填写部门');
        if (!this.formData.leaveType) throw new Error('请填写请假类型');
        if (!this.formData.plannedStartDate || !this.formData.plannedStartTime) throw new Error('请填写完整的计划开始时间');
        if (!this.formData.plannedEndDate || !this.formData.plannedEndTime) throw new Error('请填写完整的计划结束时间');

        // 处理日期时间
        const plannedStartTime = this.combineDateAndTime(this.formData.plannedStartDate, this.formData.plannedStartTime);
        const plannedEndTime = this.combineDateAndTime(this.formData.plannedEndDate, this.formData.plannedEndTime);
        const actualStartTime = this.combineDateAndTime(this.formData.actualStartDate, this.formData.actualStartTime);
        const actualEndTime = this.combineDateAndTime(this.formData.actualEndDate, this.formData.actualEndTime);

        if (!plannedStartTime || !plannedEndTime) {
          throw new Error('日期时间格式不正确');
        }

        // 创建要发送的数据对象
        const data = {
          id: this.formData.id,
          no: this.formData.no,
          name: this.formData.name,
          employeeId: this.formData.employeeId,
          department: this.formData.department,
          groupName: this.formData.groupName,
          level: this.formData.level,
          shift: this.formData.shift,
          leaveType: this.formData.leaveType,
          workAgent: this.formData.workAgent,
          reason: this.formData.reason,
          plannedStartTime,
          plannedEndTime,
          actualStartTime,
          actualEndTime,
          plannedDays: parseFloat(this.formData.plannedDays) || 0.0,
          plannedHours: parseFloat(this.formData.plannedHours) || 0.0,
          actualDays: parseFloat(this.formData.actualDays) || 0.0,
          actualHours: parseFloat(this.formData.actualHours) || 0.0,
          applicant: this.formData.applicant,
          groupApproval: this.formData.groupApproval,
          departmentSupervisorApproval: this.formData.departmentSupervisorApproval,
          departmentManagerApproval: this.formData.departmentManagerApproval,
          directorApproval: this.formData.directorApproval,
          generalManagerApproval: this.formData.generalManagerApproval,
          presidentApproval: this.formData.presidentApproval,
          managementDepartmentApproval: this.formData.managementDepartmentApproval
        };

        // 打印处理后的数据
        console.log('Processed data:', JSON.stringify(data, null, 2));

        // 根据是否有ID判断是新增还是更新
        if (this.formData.id) {
          await updateLeaveApplication(data);
          this.$message.success('更新成功');
        } else {
          await saveLeaveApplication(data);
          this.$message.success('保存成功');
        }

        this.$router.push('/main/renshi/kaoqing/qingjia-list');
      } catch (error) {
        // 打印详细错误信息
        console.error('Error details:', {
          response: error.response,
          data: error.response?.data,
          status: error.response?.status,
          message: error.message,
          headers: error.response?.headers,
          errorMessage: error.response?.headers?.['x-error-message']
        });
        this.$message.error('保存失败：' + (
          error.response?.headers?.['x-error-message'] ||
          error.response?.data?.message ||
          error.message
        ));
      }
    },
    goBack() {
      this.$router.go(-1)
    },
    printForm() {
      window.print();
    }
  }
};
</script>

<style scoped lang="scss">
/* 整体容器样式 */
.leave-application-container {
  background-color: #f4f7fa;
  padding: 20px;
  min-height: 100vh;
  font-family: '宋体', serif;
  width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
}

/* 返回按钮样式 */
.back-button {
  position: relative;
  padding: 8px 15px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  margin-left: 10px;
}

.back-button:hover {
  background-color: #e8f4ff;
}

/* 列表链接样式 */
.list-link {
  position: relative;
  padding: 8px 15px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
  text-decoration: none;
  color: #333;
  transition: background-color 0.3s ease;
}

.list-link:hover {
  background-color: #e8f4ff;
}

/* 流程按钮样式 */
.process-link {
  position: relative;
  /* 位于列表按钮右侧 */
  padding: 8px 15px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
  text-decoration: none;
  color: #333;
  transition: background-color 0.3s ease;
}

.process-link:hover {
  background-color: #e8f4ff;
}

/* 页面标题样式 */
.page-title {
  text-align: center;
  font-size: 24px;
  margin: 30px 0;
  color: #333;
}

/* 表单容器样式 */
.form-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

/* 表单标签样式 */
.form-label {
  font-size: 16px;
  margin-bottom: 10px;
}

/* NO输入框样式 */
.form-input1 {
  width: 90%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-bottom: 10px;
  text-align: left;
}

/* 表单输入框样式 */
.form-input {
  width: 90%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-bottom: 10px;
}

/* 表单文本域样式 */
.form-textarea {
  width: 90%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-bottom: 10px;
  resize: vertical;
}

/* 表格样式 */
.form-table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 20px;
}

/* 表格标签样式 */
.table-label {
  background-color: #f0f0f0;
  font-weight: bold;
}

/* 表格单元格样式 */
.form-table th,
.form-table td {
  border: 1px solid #ccc;
  padding: 10px;
  text-align: center;
}

/* 保存按钮样式 */
.save-button {
  padding: 10px 20px;
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.save-button:hover {
  background-color: #2f80ed;
}

/* 附加说明部分样式 */
.additional-info {
  margin-top: 20px;
  font-size: 14px;
  color: #666;
  text-align: left;
  line-height: 2em;
}

@media print {

  /*@page规则被用来设置打印页面的方向为横向*/
  // @page {
  //   size: landscape;
  // }
  .container {
    width: 280mm;
  }

  .form-container {
    padding: 20px 10px 20px 1px;
    margin-right: 5px;
    box-shadow: 0 0px 0px rgba(255, 255, 255, 0) !important;
  }

  .button-group {
    display: none;
  }


  .page-header,
  .save-button {
    display: none;
  }

  .main-form {
    box-shadow: none;
    padding: 10px;
  }

  .additional-info {
    margin-top: 0px;
  }

  table {
    margin: 0px 0px;
  }

  .info-table,
  .content-table,
  .approval-table {
    border: 1px solid #000;

    td,
    th {
      border: 1px solid #000;
    }
  }

  td,
  th {
    padding: 5px;
    border: 1px solid #000;
  }

  input {
    border: none !important;
    background-color: transparent !important;
    text-align: center;
  }

  textarea {
    border: 0px !important;
  }
}
</style>